// src/pages/Broadcasts.js - 全球广播页面

import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Typography, Card, List, Space, Tag, Button, Tabs, Modal, Form,
  Input, Select, message, Avatar, Badge, Tooltip, Row, Col,
  Statistic, Popconfirm, Empty, Divider, Drawer
} from 'antd';
import {
  GlobalOutlined, PlusOutlined, FireOutlined, ClockCircleOutlined,
  SearchOutlined, GiftOutlined, UserOutlined, CommentOutlined,
  EyeOutlined, StarOutlined, DeleteOutlined, EditOutlined, FilterOutlined,
  LinkOutlined
} from '@ant-design/icons';
import { broadcasts, points } from '../services';
import ResourceSelector from '../components/ResourceSelector';

const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;
const { Option } = Select;
const { TabPane } = Tabs;

const Broadcasts = () => {
  const navigate = useNavigate();
  const [broadcastsList, setBroadcastsList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [isCreateModalVisible, setIsCreateModalVisible] = useState(false);
  const [isSearchDrawerVisible, setIsSearchDrawerVisible] = useState(false);
  const [activeTab, setActiveTab] = useState('all');
  const [searchFilters, setSearchFilters] = useState({});
  const [isSearchMode, setIsSearchMode] = useState(false);
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [messageApi, contextHolder] = message.useMessage();
  const [currentUser, setCurrentUser] = useState(null);
  const [likedBroadcasts, setLikedBroadcasts] = useState(new Set());
  const [isResourceSelectorVisible, setIsResourceSelectorVisible] = useState(false);
  const [selectedResource, setSelectedResource] = useState(null);
  const [currentBroadcastType, setCurrentBroadcastType] = useState('');
  const [isResourceViewerVisible, setIsResourceViewerVisible] = useState(false);
  const [currentResourceData, setCurrentResourceData] = useState(null);

  const broadcastTypes = [
    { value: '资源分享', label: '资源分享', color: '#52c41a', icon: GiftOutlined },
    { value: '种子求助', label: '种子求助', color: '#ff4d4f', icon: SearchOutlined },
    { value: '公告通知', label: '公告通知', color: '#1890ff', icon: GlobalOutlined }
  ];

  useEffect(() => {
    // 如果在搜索模式下，切换标签页时清除搜索
    if (isSearchMode) {
      setIsSearchMode(false);
      setSearchFilters({});
      searchForm.resetFields();
    }
    loadBroadcasts();
    loadCurrentUser();
  }, [activeTab]);

  const loadCurrentUser = () => {
    const user = JSON.parse(localStorage.getItem('starrypt_user') || 'null');
    setCurrentUser(user);
  };

  const loadBroadcasts = async (isSearch = false, searchParams = {}) => {
    try {
      setLoading(true);
      let response;

      if (isSearch) {
        // 使用搜索接口
        response = await broadcasts.searchBroadcasts(searchParams);
      } else {
        // 使用普通列表接口
        response = await broadcasts.getBroadcasts();
      }

      if (response.success) {
        let filteredBroadcasts = response.data.broadcasts || [];

        // 只有在非搜索模式下才根据标签页筛选
        if (!isSearch && activeTab !== 'all') {
          filteredBroadcasts = filteredBroadcasts.filter(broadcast =>
            broadcast.type === activeTab || broadcast.category === activeTab
          );
        }

        // 按优先级和创建时间排序
        filteredBroadcasts.sort((a, b) => {
          // 置顶优先
          if (a.isPinned !== b.isPinned) return b.isPinned - a.isPinned;
          // 热门优先
          if (a.isHot !== b.isHot) return b.isHot - a.isHot;
          // 点赞数优先
          if (a.likes !== b.likes) return b.likes - a.likes;
          // 最新优先
          return new Date(b.createTime) - new Date(a.createTime);
        });

        setBroadcastsList(filteredBroadcasts);
        setIsSearchMode(isSearch);
        if (isSearch) {
          setSearchFilters(searchParams);
        }

        // 保留现有的点赞状态
        const currentLikedSet = new Set(likedBroadcasts);
        filteredBroadcasts.forEach(broadcast => {
          if (broadcast.isLiked) {
            currentLikedSet.add(broadcast.id || broadcast.broadcastId);
          }
        });
        setLikedBroadcasts(currentLikedSet);
      } else {
        messageApi.error(isSearch ? '搜索广播失败' : '加载广播失败');
      }
    } catch (error) {
      console.error(isSearch ? '搜索广播失败:' : '加载广播失败:', error);
      messageApi.error((isSearch ? '搜索广播失败: ' : '加载广播失败: ') + error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateBroadcast = async (values) => {
    try {
      // 构建资源链接
      let resourceUrl = null;
      if (selectedResource) {
        // 使用选中的资源生成完整的网站链接
        resourceUrl = `${window.location.origin}${selectedResource.detailUrl}`;
        console.log('✅ 使用选中的资源链接:', resourceUrl);
      } else if (values.resourceUrl) {
        // 兼容手动输入的链接
        resourceUrl = values.resourceUrl;
        console.log('✅ 使用手动输入的链接:', resourceUrl);
      }

      const response = await broadcasts.createBroadcast({
        title: values.title,
        content: values.content,
        type: values.type,
        category: values.type, // 后端期望category字段
        tags: values.tags ? (Array.isArray(values.tags) ? values.tags.join(',') : values.tags) : '',
        resourceUrl: resourceUrl
      });

      if (response.success) {
        messageApi.success(response.message || '广播发布成功！');
        setIsCreateModalVisible(false);
        form.resetFields();
        setSelectedResource(null);
        setCurrentBroadcastType('');
        loadBroadcasts();
      } else {
        messageApi.error(response.message || '发布广播失败');
      }
    } catch (error) {
      console.error('发布广播失败:', error);
      messageApi.error('发布广播失败: ' + error.message);
    }
  };

  const handleLikeBroadcast = async (broadcastId) => {
    // 获取当前点赞状态
    const isCurrentlyLiked = likedBroadcasts.has(broadcastId);

    // 保存原始点赞数，用于错误恢复
    const originalBroadcast = broadcastsList.find(b => (b.id || b.broadcastId) === broadcastId);
    const originalLikes = originalBroadcast?.likes || 0;

    try {

      // 立即更新UI状态
      const newLikedSet = new Set(likedBroadcasts);
      if (isCurrentlyLiked) {
        newLikedSet.delete(broadcastId);
      } else {
        newLikedSet.add(broadcastId);
      }
      setLikedBroadcasts(newLikedSet);

      // 立即更新本地广播列表中的点赞数
      setBroadcastsList(prevList =>
        prevList.map(broadcast => {
          if ((broadcast.id || broadcast.broadcastId) === broadcastId) {
            return {
              ...broadcast,
              likes: isCurrentlyLiked
                ? Math.max(0, originalLikes - 1)  // 取消点赞，点赞数-1
                : originalLikes + 1               // 点赞，点赞数+1
            };
          }
          return broadcast;
        })
      );

      // 调用API
      const response = await broadcasts.likeBroadcast(broadcastId);
      if (response.success) {
        messageApi.success(response.data.liked ? '点赞成功' : '取消点赞成功');

        // 如果后端返回了准确的点赞数，更新本地数据
        if (response.data.likes !== undefined) {
          setBroadcastsList(prevList =>
            prevList.map(broadcast => {
              if ((broadcast.id || broadcast.broadcastId) === broadcastId) {
                return {
                  ...broadcast,
                  likes: response.data.likes
                };
              }
              return broadcast;
            })
          );
        }
      } else {
        // API调用失败，恢复所有状态
        setLikedBroadcasts(likedBroadcasts);
        setBroadcastsList(prevList =>
          prevList.map(broadcast => {
            if ((broadcast.id || broadcast.broadcastId) === broadcastId) {
              return {
                ...broadcast,
                likes: originalLikes // 使用之前保存的原始点赞数
              };
            }
            return broadcast;
          })
        );
        messageApi.error(response.message || '操作失败');
      }
    } catch (error) {
      // API调用失败，恢复所有状态
      setLikedBroadcasts(likedBroadcasts);
      setBroadcastsList(prevList =>
        prevList.map(broadcast => {
          if ((broadcast.id || broadcast.broadcastId) === broadcastId) {
            return {
              ...broadcast,
              likes: originalLikes // 使用之前保存的原始点赞数
            };
          }
          return broadcast;
        })
      );
      console.error('点赞操作失败:', error);
      messageApi.error('操作失败: ' + error.message);
    }
  };

  const handleSearch = async (values) => {
    const searchParams = {};

    if (values.category) {
      searchParams.category = values.category;
    }

    if (values.tags) {
      searchParams.tags = values.tags.trim();
    }

    if (values.hasResource !== undefined) {
      searchParams.hasResource = values.hasResource;
    }

    await loadBroadcasts(true, searchParams);
    setIsSearchDrawerVisible(false);
    messageApi.success('搜索完成');
  };

  const handleClearSearch = () => {
    setIsSearchMode(false);
    setSearchFilters({});
    searchForm.resetFields();
    loadBroadcasts();
    messageApi.success('已清除搜索条件');
  };

  // 处理资源选择
  const handleResourceSelect = (resourceInfo) => {
    setSelectedResource(resourceInfo);
    setIsResourceSelectorVisible(false);

    // 更新表单中的资源链接字段显示
    form.setFieldsValue({
      resourceUrl: `${resourceInfo.title} (${resourceInfo.category})`
    });

    messageApi.success(`已选择资源: ${resourceInfo.title}`);
    console.log('✅ 资源选择完成:', resourceInfo);
  };

  // 处理广播类型变化
  const handleBroadcastTypeChange = (type) => {
    setCurrentBroadcastType(type);

    // 如果切换到"种子求助"或"公告通知"，清除已选择的资源
    if (type === '种子求助' || type === '公告通知') {
      setSelectedResource(null);
      form.setFieldsValue({ resourceUrl: '' });
      console.log('🚫 当前广播类型不需要资源链接:', type);
    }
  };

  // 检查当前广播类型是否需要显示资源选择
  const shouldShowResourceSelector = () => {
    return currentBroadcastType === '资源分享';
  };

  const handleViewResource = (broadcast) => {
    console.log('点击查看资源，广播数据:', broadcast);

    // 设置资源数据
    const resourceData = {
      id: broadcast.id,
      title: broadcast.title,
      content: broadcast.content,
      resourceUrl: broadcast.resourceUrl,
      resourceType: broadcast.resourceType,
      resourceSize: broadcast.resourceSize,
      author: broadcast.author,
      createTime: broadcast.createTime,
      tags: broadcast.tags,
      likes: broadcast.likes,
      downloads: broadcast.downloads,
      views: broadcast.views
    };

    setCurrentResourceData(resourceData);
    setIsResourceViewerVisible(true);
  };

  const getBroadcastTypeInfo = (type) => {
    return broadcastTypes.find(t => t.value === type) || broadcastTypes[0];
  };

  const formatTime = (timeString) => {
    const time = new Date(timeString);
    const now = new Date();
    const diffInSeconds = Math.floor((now - time) / 1000);

    if (diffInSeconds < 60) return '刚刚';
    if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)}分钟前`;
    if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)}小时前`;
    return time.toLocaleDateString();
  };

  return (
    <div style={{ background: '#f0f2f5', minHeight: 'calc(100vh - 200px)' }}>
      {contextHolder}
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '24px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
          <Title level={2} style={{ margin: 0 }}>
            <GlobalOutlined /> 全球广播
            {isSearchMode && (
              <Tag color="blue" style={{ marginLeft: 8 }}>
                搜索模式
              </Tag>
            )}
          </Title>
          <Space>
            <Button
              icon={<FilterOutlined />}
              onClick={() => setIsSearchDrawerVisible(true)}
            >
              搜索筛选
            </Button>
            {isSearchMode && (
              <Button
                onClick={handleClearSearch}
              >
                清除搜索
              </Button>
            )}
            <Button
              type="primary"
              icon={<PlusOutlined />}
              size="large"
              onClick={() => setIsCreateModalVisible(true)}
              style={{
                background: 'linear-gradient(135deg, rgba(102, 126, 234) 0%, rgba(118, 75, 162) 100%)',
                border: 'none',
                color: 'white',
                fontWeight: 'bold'
              }}
            >
              发布广播
            </Button>
          </Space>
        </div>

        <Card>
          <Tabs
            activeKey={activeTab}
            onChange={setActiveTab}
            size="large"
            style={{ marginBottom: 24 }}
          >
            <TabPane tab="全部广播" key="all" />
            {broadcastTypes.map(type => {
              const IconComponent = type.icon;
              return (
                <TabPane
                  tab={
                    <span>
                      <IconComponent /> {type.label}
                    </span>
                  }
                  key={type.value}
                />
              );
            })}
          </Tabs>

          <List
            loading={loading}
            dataSource={broadcastsList}
            locale={{
              emptyText: (
                <Empty description="暂无广播">
                  <Button type="primary" onClick={() => setIsCreateModalVisible(true)}>
                    发布第一条广播
                  </Button>
                </Empty>
              )
            }}
            renderItem={broadcast => {
              const typeInfo = getBroadcastTypeInfo(broadcast.type || broadcast.category);
              const IconComponent = typeInfo.icon;

              return (
                <List.Item
                  style={{ padding: '20px 0' }}
                  actions={[
                    <Button
                      type="text"
                      icon={<StarOutlined style={{
                        color: likedBroadcasts.has(broadcast.id || broadcast.broadcastId) ? '#ff4d4f' : '#8c8c8c'
                      }} />}
                      onClick={() => handleLikeBroadcast(broadcast.id || broadcast.broadcastId)}
                      style={{
                        color: likedBroadcasts.has(broadcast.id || broadcast.broadcastId) ? '#ff4d4f' : '#8c8c8c'
                      }}
                    >
                      {broadcast.likes || 0}
                    </Button>,
                    <Button
                      type="text"
                      icon={<EyeOutlined />}
                    >
                      {broadcast.views || 0}
                    </Button>
                  ]}
                >
                  <List.Item.Meta
                    avatar={
                      <Badge dot={broadcast.isHot} color="red">
                        <Avatar
                          style={{ backgroundColor: typeInfo.color }}
                          icon={<IconComponent />}
                          size="large"
                        />
                      </Badge>
                    }
                    title={
                      <div>
                        <Text strong style={{ fontSize: '16px' }}>{broadcast.title}</Text>
                        <Tag color={typeInfo.color} style={{ marginLeft: 8 }}>
                          {typeInfo.label}
                        </Tag>
                        {broadcast.hasResource && broadcast.resourceUrl && (
                          <Tag
                            color="green"
                            style={{ marginLeft: 4, cursor: 'pointer' }}
                            onClick={(e) => {
                              e.stopPropagation();
                              handleViewResource(broadcast);
                            }}
                          >
                            <LinkOutlined /> 查看资源
                          </Tag>
                        )}
                        {broadcast.hasResource && !broadcast.resourceUrl && (
                          <Tag color="green" style={{ marginLeft: 4 }}>
                            <GiftOutlined /> 有资源
                          </Tag>
                        )}
                        {broadcast.isHot && (
                          <Tag color="red" style={{ marginLeft: 4 }}>
                            <FireOutlined /> 热门
                          </Tag>
                        )}
                      </div>
                    }
                    description={
                      <div>
                        <Paragraph
                          ellipsis={{ rows: 3, expandable: true }}
                          style={{ marginBottom: 8 }}
                        >
                          {broadcast.content}
                        </Paragraph>
                        <Space wrap>
                          <Text type="secondary">
                            <UserOutlined /> {broadcast.author || broadcast.username}
                          </Text>
                          {broadcast.authorLevel && (
                            <Tag color="blue">{broadcast.authorLevel}</Tag>
                          )}
                          <Text type="secondary">
                            <ClockCircleOutlined /> {formatTime(broadcast.createTime)}
                          </Text>
                          {broadcast.tags && broadcast.tags.length > 0 && (
                            <Space size={4}>
                              {(Array.isArray(broadcast.tags) ? broadcast.tags : broadcast.tags.split(',')).slice(0, 3).map((tag, index) => (
                                <Tag key={index} size="small">{tag.trim()}</Tag>
                              ))}
                            </Space>
                          )}
                        </Space>
                      </div>
                    }
                  />
                </List.Item>
              );
            }}
          />
        </Card>

        {/* 创建广播模态框 */}
        <Modal
          title="发布广播"
          open={isCreateModalVisible}
          onCancel={() => {
            setIsCreateModalVisible(false);
            form.resetFields();
            setSelectedResource(null);
            setCurrentBroadcastType('');
          }}
          footer={null}
          width={600}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleCreateBroadcast}
          >
            <Form.Item
              name="type"
              label="广播类型"
              rules={[{ required: true, message: '请选择广播类型' }]}
            >
              <Select
                placeholder="选择广播类型"
                onChange={handleBroadcastTypeChange}
              >
                {broadcastTypes.map(type => {
                  const IconComponent = type.icon;
                  return (
                    <Option key={type.value} value={type.value}>
                      <IconComponent style={{ color: type.color }} /> {type.label}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>

            <Form.Item
              name="title"
              label="标题"
              rules={[{ required: true, message: '请输入标题' }]}
            >
              <Input placeholder="输入广播标题" />
            </Form.Item>

            <Form.Item
              name="content"
              label="内容"
              rules={[{ required: true, message: '请输入内容' }]}
            >
              <TextArea
                placeholder="详细描述你的需求或分享的内容"
                rows={6}
              />
            </Form.Item>

            <Form.Item name="tags" label="标签">
              <Input placeholder="添加相关标签，用逗号分隔" />
            </Form.Item>

            {/* 根据广播类型显示不同的资源链接字段 */}
            {shouldShowResourceSelector() ? (
              <Form.Item name="resourceUrl" label="资源链接">
                <Input.Group compact>
                  <Input
                    style={{ width: 'calc(100% - 120px)' }}
                    placeholder={selectedResource ? `已选择: ${selectedResource.title}` : "请选择资源广场中的资源"}
                    value={selectedResource ? `${selectedResource.title} (${selectedResource.category})` : ''}
                    readOnly
                  />
                  <Button
                    type="primary"
                    style={{ width: 120 }}
                    icon={<LinkOutlined />}
                    onClick={() => setIsResourceSelectorVisible(true)}
                  >
                    选择资源
                  </Button>
                </Input.Group>
                {selectedResource && (
                  <div style={{ marginTop: 8, fontSize: 12, color: '#666' }}>
                    💡 已选择资源链接: {selectedResource.detailUrl}
                    <Button
                      type="link"
                      size="small"
                      onClick={() => {
                        setSelectedResource(null);
                        form.setFieldsValue({ resourceUrl: '' });
                      }}
                    >
                      清除选择
                    </Button>
                  </div>
                )}
              </Form.Item>
            ) : currentBroadcastType === '种子求助' ? (
              <div style={{
                padding: 12,
                background: '#f0f2f5',
                borderRadius: 6,
                border: '1px dashed #d9d9d9',
                textAlign: 'center',
                color: '#666'
              }}>
                <SearchOutlined style={{ fontSize: 24, marginBottom: 8, color: '#ff4d4f' }} />
                <div>种子求助类型无需选择资源链接</div>
                <div style={{ fontSize: 12, marginTop: 4 }}>请在内容中详细描述您需要的资源</div>
              </div>
            ) : currentBroadcastType === '公告通知' ? (
              <div style={{
                padding: 12,
                background: '#f0f9ff',
                borderRadius: 6,
                border: '1px dashed #91d5ff',
                textAlign: 'center',
                color: '#666'
              }}>
                <GlobalOutlined style={{ fontSize: 24, marginBottom: 8, color: '#1890ff' }} />
                <div>公告通知类型无需选择资源链接</div>
                <div style={{ fontSize: 12, marginTop: 4 }}>请在内容中发布您的公告信息</div>
              </div>
            ) : (
              <Form.Item name="resourceUrl" label="资源链接">
                <Input placeholder="请先选择广播类型" disabled />
              </Form.Item>
            )}

            <Form.Item style={{ textAlign: 'right' }}>
              <Button onClick={() => setIsCreateModalVisible(false)}>
                取消
              </Button>
              <Button type="primary" htmlType="submit" style={{ marginLeft: 8 }}>
                发布广播
              </Button>
            </Form.Item>
          </Form>
        </Modal>

        {/* 资源选择器 */}
        <ResourceSelector
          visible={isResourceSelectorVisible}
          onCancel={() => setIsResourceSelectorVisible(false)}
          onSelect={handleResourceSelect}
          selectedResource={selectedResource}
        />

        {/* 资源查看器Modal */}
        <Modal
          title={
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <LinkOutlined style={{ color: '#52c41a' }} />
              <span>资源详情</span>
            </div>
          }
          open={isResourceViewerVisible}
          onCancel={() => {
            setIsResourceViewerVisible(false);
            setCurrentResourceData(null);
          }}
          width={800}
          footer={[
            <Button key="close" onClick={() => setIsResourceViewerVisible(false)}>
              关闭
            </Button>,
            currentResourceData?.resourceUrl && (
              <Button
                key="open"
                type="primary"
                icon={<LinkOutlined />}
                onClick={() => {
                  console.log('跳转到资源链接:', currentResourceData.resourceUrl);
                  if (currentResourceData.resourceUrl.startsWith('http')) {
                    window.open(currentResourceData.resourceUrl, '_blank');
                  } else {
                    messageApi.warning('资源链接格式不正确');
                  }
                }}
              >
                跳转到资源
              </Button>
            )
          ]}
        >
          {currentResourceData && (
            <div style={{ padding: '16px 0' }}>
              {/* 资源基本信息 */}
              <Card size="small" style={{ marginBottom: 16 }}>
                <Row gutter={[16, 16]}>
                  <Col span={24}>
                    <Title level={4} style={{ margin: 0, color: '#1890ff' }}>
                      {currentResourceData.title}
                    </Title>
                  </Col>
                  <Col span={12}>
                    <Statistic
                      title="资源作者"
                      value={currentResourceData.author}
                      prefix={<UserOutlined />}
                    />
                  </Col>
                  <Col span={12}>
                    <Statistic
                      title="发布时间"
                      value={formatTime(currentResourceData.createTime)}
                      prefix={<ClockCircleOutlined />}
                    />
                  </Col>
                  <Col span={8}>
                    <Statistic
                      title="点赞数"
                      value={currentResourceData.likes || 0}
                      prefix={<StarOutlined style={{ color: '#faad14' }} />}
                    />
                  </Col>
                  <Col span={8}>
                    <Statistic
                      title="下载数"
                      value={currentResourceData.downloads || 0}
                      prefix={<GiftOutlined style={{ color: '#52c41a' }} />}
                    />
                  </Col>
                  <Col span={8}>
                    <Statistic
                      title="浏览数"
                      value={currentResourceData.views || 0}
                      prefix={<EyeOutlined style={{ color: '#722ed1' }} />}
                    />
                  </Col>
                </Row>
              </Card>

              {/* 资源描述 */}
              <Card size="small" title="资源描述" style={{ marginBottom: 16 }}>
                <Paragraph>
                  {currentResourceData.content || '暂无描述'}
                </Paragraph>
              </Card>

              {/* 资源详细信息 */}
              <Card size="small" title="资源信息">
                <Row gutter={[16, 8]}>
                  <Col span={12}>
                    <Text strong>资源类型：</Text>
                    <Tag color="blue">
                      {currentResourceData.resourceType || '未知'}
                    </Tag>
                  </Col>
                  <Col span={12}>
                    <Text strong>资源大小：</Text>
                    <Tag color="green">
                      {currentResourceData.resourceSize || '未知'}
                    </Tag>
                  </Col>
                  <Col span={24} style={{ marginTop: 8 }}>
                    <Text strong>资源链接：</Text>
                    <div style={{
                      marginTop: 4,
                      padding: 8,
                      background: '#f5f5f5',
                      borderRadius: 4,
                      wordBreak: 'break-all'
                    }}>
                      {currentResourceData.resourceUrl || '暂无链接'}
                    </div>
                  </Col>
                  {currentResourceData.tags && currentResourceData.tags.length > 0 && (
                    <Col span={24} style={{ marginTop: 8 }}>
                      <Text strong>标签：</Text>
                      <div style={{ marginTop: 4 }}>
                        <Space wrap>
                          {(Array.isArray(currentResourceData.tags)
                            ? currentResourceData.tags
                            : currentResourceData.tags.split(',')
                          ).map((tag, index) => (
                            <Tag key={index} color="purple">
                              {tag.trim()}
                            </Tag>
                          ))}
                        </Space>
                      </div>
                    </Col>
                  )}
                </Row>
              </Card>
            </div>
          )}
        </Modal>

        {/* 搜索筛选抽屉 */}
        <Drawer
          title="搜索筛选"
          open={isSearchDrawerVisible}
          onClose={() => setIsSearchDrawerVisible(false)}
          width={400}
          footer={
            <div style={{ textAlign: 'right' }}>
              <Button onClick={() => setIsSearchDrawerVisible(false)} style={{ marginRight: 8 }}>
                取消
              </Button>
              <Button type="primary" onClick={() => searchForm.submit()}>
                搜索
              </Button>
            </div>
          }
        >
          <Form
            form={searchForm}
            layout="vertical"
            onFinish={handleSearch}
          >
            <Form.Item
              name="category"
              label="分类"
            >
              <Select placeholder="选择广播分类" allowClear>
                {broadcastTypes.map(type => {
                  const IconComponent = type.icon;
                  return (
                    <Option key={type.value} value={type.value}>
                      <IconComponent style={{ color: type.color }} /> {type.label}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>

            <Form.Item
              name="tags"
              label="标签"
              help="输入要搜索的标签，支持多个关键词"
            >
              <Input
                placeholder="如：BT、资源、游戏等"
                allowClear
              />
            </Form.Item>

            <Form.Item
              name="hasResource"
              label="资源筛选"
            >
              <Select placeholder="是否包含资源" allowClear>
                <Option value={true}>包含资源</Option>
                <Option value={false}>不包含资源</Option>
              </Select>
            </Form.Item>

            {isSearchMode && Object.keys(searchFilters).length > 0 && (
              <Card size="small" title="当前搜索条件" style={{ marginTop: 16 }}>
                <Space direction="vertical" style={{ width: '100%' }}>
                  {searchFilters.category && (
                    <div>
                      <strong>分类：</strong>
                      <Tag color="blue">{searchFilters.category}</Tag>
                    </div>
                  )}
                  {searchFilters.tags && (
                    <div>
                      <strong>标签：</strong>
                      <Tag color="green">{searchFilters.tags}</Tag>
                    </div>
                  )}
                  {searchFilters.hasResource !== undefined && (
                    <div>
                      <strong>资源：</strong>
                      <Tag color={searchFilters.hasResource ? 'orange' : 'purple'}>
                        {searchFilters.hasResource ? '包含资源' : '不包含资源'}
                      </Tag>
                    </div>
                  )}
                </Space>
              </Card>
            )}
          </Form>
        </Drawer>
      </div>
    </div>
  );
};

export default Broadcasts;
